#include "cashier.h"
#include "productdao.h"
#include "memberdao.h"
#include "inventorydao.h"
#include "orderdao.h"
#include "orderservice.h"
#include "paymentprocessor.h"
#include "shoppingcart.h"
#include <QHeaderView>
#include <QTreeWidgetItem>
#include <QFont>
#include <QApplication>
#include <QScreen>
#include <QDateTime>
#include <QKeySequence>
#include <QMessageBox>
#include "appinitializer.h"
#include <QDialogButtonBox>
#include <QDebug>
#include <QTimer>

// 构造函数
CashierDialog::CashierDialog(
    ProductDAO* productDAO,
    MemberDAO* memberDAO,
    InventoryDAO* inventoryDAO,
    OrderService* orderService,
    PaymentProcessor* paymentProcessor,
    QWidget* parent
) : QDialog(parent),
    m_productDAO(productDAO)  // 外部传入指针直接赋值（所有权归外部，不修改）
{
    // 设置为独立窗口（原逻辑保留）
    setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
    // 设置绿色主题样式表
    setStyleSheet(R"(
        QDialog {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #f8fffe, stop:1 #e8f5e8);
        }
        QLabel {
            color: #2d5016;
            font: 10pt "Microsoft YaHei";
        }
        QLabel#totalAmountLabel {
            color: #1b5e20;
            font: bold 18pt "Microsoft YaHei";
            background-color: rgba(200, 230, 201, 0.3);
            border: 2px solid #4caf50;
            border-radius: 8px;
            padding: 8px;
        }
        QLabel#titleLabel {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                stop:0 #2e7d32, stop:0.5 #388e3c, stop:1 #43a047);
            color: white;
            border-radius: 12px;
            font: bold 26pt "Microsoft YaHei";
            text-align: center;
        }
        QLineEdit {
            color: #1b5e20;
            background-color: #f1f8e9;
            border: 2px solid #81c784;
            border-radius: 6px;
            padding: 6px;
            font: 10pt "Microsoft YaHei";
            selection-background-color: #a5d6a7;
        }
        QLineEdit:focus {
            border: 2px solid #4caf50;
            background-color: #e8f5e9;
        }
        QPushButton {
            color: #1b5e20;
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #e8f5e9, stop:1 #c8e6c9);
            border: 2px solid #81c784;
            border-radius: 6px;
            padding: 8px 12px;
            font: 10pt "Microsoft YaHei";
            min-height: 20px;
        }
        QPushButton:hover {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #c8e6c9, stop:1 #a5d6a7);
            border: 2px solid #66bb6a;
        }
        QPushButton:pressed {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #a5d6a7, stop:1 #81c784);
            border: 2px solid #4caf50;
        }
        QPushButton:disabled {
            color: #9e9e9e;
            background-color: #f5f5f5;
            border: 2px solid #e0e0e0;
        }
        QPushButton#operationButton {
            min-width: 80px;
            font: bold 10pt "Microsoft YaHei";
        }
        QTableWidget {
            color: #1b5e20;
            background-color: #f9fbe7;
            gridline-color: #c5e1a5;
            font: 10pt "Microsoft YaHei";
            border: 2px solid #81c784;
            border-radius: 8px;
            selection-background-color: #dcedc8;
        }
        QHeaderView::section {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #c8e6c9, stop:1 #a5d6a7);
            color: #1b5e20;
            padding: 8px;
            font: bold 11pt "Microsoft YaHei";
            border: 1px solid #81c784;
        }
        QTreeWidget {
            color: #1b5e20;
            background-color: #f9fbe7;
            font: 10pt "Microsoft YaHei";
            border: 2px solid #81c784;
            border-radius: 8px;
            selection-background-color: #dcedc8;
        }
        QTreeWidget::item {
            padding: 6px;
            border-bottom: 1px solid #e0e0e0;
        }
        QTreeWidget::item:hover {
            background-color: #e8f5e9;
        }
        QTreeWidget::item:selected {
            background-color: #c8e6c9;
        }
        QGroupBox {
            border: 2px solid #81c784;
            border-radius: 10px;
            margin-top: 12px;
            font: bold 11pt "Microsoft YaHei";
            color: #2e7d32;
            background-color: rgba(248, 255, 254, 0.8);
        }
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 15px;
            padding: 0 8px 0 8px;
            background-color: #e8f5e9;
            border-radius: 4px;
        }
        QRadioButton {
            font: 10pt "Microsoft YaHei";
            margin: 6px;
            color: #1b5e20;
        }
        QRadioButton::indicator {
            width: 16px;
            height: 16px;
        }
        QRadioButton::indicator:unchecked {
            border: 2px solid #81c784;
            border-radius: 8px;
            background-color: #f1f8e9;
        }
        QRadioButton::indicator:checked {
            border: 2px solid #4caf50;
            border-radius: 8px;
            background: qradialgradient(cx:0.5, cy:0.5, radius:0.4,
                stop:0 #4caf50, stop:1 #81c784);
        }
        QDoubleSpinBox {
            font: 10pt "Microsoft YaHei";
            padding: 6px;
            border: 2px solid #81c784;
            border-radius: 6px;
            background-color: #f1f8e9;
            color: #1b5e20;
            selection-background-color: #a5d6a7;
        }
        QDoubleSpinBox:focus {
            border: 2px solid #4caf50;
            background-color: #e8f5e9;
        }
        QDoubleSpinBox::up-button, QDoubleSpinBox::down-button {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #e8f5e9, stop:1 #c8e6c9);
            border: 1px solid #81c784;
        }
        QDoubleSpinBox::up-button:hover, QDoubleSpinBox::down-button:hover {
            background-color: #c8e6c9;
        }
    )");
    // 设置窗口标题（原逻辑保留）
    setWindowTitle("超市收银系统");
    // 获取屏幕尺寸并调整窗口大小（原逻辑保留）
    QScreen *primaryScreen = QApplication::primaryScreen();
    QRect screenGeometry = primaryScreen->geometry();
    int windowWidth = screenGeometry.width() - 20;
    int windowHeight = screenGeometry.height() - 50;  // 适当减少高度避免超出屏幕
    setGeometry(
        screenGeometry.x() + 10,
        screenGeometry.y() + 10,
        windowWidth,
        windowHeight
    );
    // 创建滚动区域和内容容器
    scrollArea = new QScrollArea(this);
    contentWidget = new QWidget();
    
    // 初始化主布局应用到内容容器
    mainLayout = new QVBoxLayout(contentWidget);
    mainLayout->setSpacing(2);  // 减少间距从5到2
    mainLayout->setContentsMargins(5, 5, 5, 5);  // 减少边距从10到5
    
    // 设置滚动区域属性
    scrollArea->setWidget(contentWidget);
    scrollArea->setWidgetResizable(true);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    
    // 创建对话框的主布局
    QVBoxLayout *dialogLayout = new QVBoxLayout(this);
    dialogLayout->setContentsMargins(0, 0, 0, 0);
    dialogLayout->addWidget(scrollArea);
    
    // 初始化界面（原逻辑保留）
    setupUI();

    // -------------------------- 智能指针修改开始 --------------------------
    // 1. 内部对象初始化：new → std::make_unique（智能指针自动管理内存）
    m_shoppingCart = std::make_unique<ShoppingCart>(this);  // 修改：原始指针→unique_ptr
    m_memberDAO = std::make_unique<MemberDAO>(AppInitializer::database());  // 修改：new→make_unique
    m_inventoryDAO = std::make_unique<InventoryDAO>(AppInitializer::database());  // 修改：new→make_unique
    m_paymentProcessor = std::make_unique<PaymentProcessor>(this);  // 修改：new→make_unique
    m_paymentProcessor->setMemberDAO(m_memberDAO.get());  // 修改：智能指针转原始指针（用get()）

    // 2. 订单服务初始化（局部对象也用智能指针）
    m_orderService = std::make_unique<OrderService>(this);  // 修改：new→make_unique
    auto orderDAO = std::make_unique<OrderDAO>(AppInitializer::database());  // 修改：局部对象用unique_ptr
    m_orderService->setOrderDAO(orderDAO.release());  // 修改：转移所有权（release()释放智能指针控制权）
    m_orderService->setProductDAO(m_productDAO);
    m_orderService->setInventoryDAO(m_inventoryDAO.get());  // 修改：智能指针转原始指针
    // -------------------------- 智能指针修改结束 --------------------------

    // 初始化订单显示（原逻辑保留）
    resetOrderDisplay();
    // 动画效果初始化（原逻辑保留，m_statusAnimation在initAnimations中初始化）
    initAnimations();

    // -------------------------- 智能指针修改开始 --------------------------
    // 3. 信号连接：智能指针需用get()获取原始指针
    connect(m_paymentProcessor.get(), &PaymentProcessor::paymentCompleted,  // 修改：get()转原始指针
            this, &CashierDialog::onPaymentCompleted);
    connect(m_paymentProcessor.get(), &PaymentProcessor::errorOccurred,  // 修改：get()转原始指针
            this, [this](const QString& msg) {
        QMessageBox::critical(this, "支付错误", msg);
    });
    connect(m_shoppingCart.get(), &ShoppingCart::cartUpdated,  // 修改：get()转原始指针
            this, &CashierDialog::onCartUpdated);
    // 订单服务信号连接（修改：get()转原始指针）
    connect(m_orderService.get(), &OrderService::orderCreated,  // 修改：get()转原始指针
            this, &CashierDialog::onOrderCreated);
    connect(m_orderService.get(), &OrderService::orderPaid,  // 修改：get()转原始指针
            this, &CashierDialog::onOrderPaid);
    connect(m_orderService.get(), &OrderService::errorOccurred,  // 修改：get()转原始指针
            this, &CashierDialog::onOrderError);
    // -------------------------- 智能指针修改结束 --------------------------

    // 其他信号连接（原逻辑保留，无智能指针修改）
    connect(codeEdit, &QLineEdit::returnPressed, this, &CashierDialog::onCodeEditReturnPressed);
    connect(checkoutButton, &QPushButton::clicked, this, &CashierDialog::onCheckoutButtonClicked);
    connect(modifyPriceButton, &QPushButton::clicked, this, &CashierDialog::onClearCartButtonClicked);
    connect(memberCardEdit, &QLineEdit::returnPressed, this, &CashierDialog::onMemberCardEditReturnPressed);
    connect(clearCardButton, &QPushButton::clicked, this, &CashierDialog::onClearCardButtonClicked);
    connect(paidAmountSpin, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
            this, &CashierDialog::onPaidAmountChanged);
    connect(cashRadio, &QRadioButton::toggled, this, &CashierDialog::onPaymentMethodChanged);
    connect(cardRadio, &QRadioButton::toggled, this, &CashierDialog::onPaymentMethodChanged);
    connect(wechatRadio, &QRadioButton::toggled, this, &CashierDialog::onPaymentMethodChanged);
    connect(alipayRadio, &QRadioButton::toggled, this, &CashierDialog::onPaymentMethodChanged);
    connect(memberBalanceRadio, &QRadioButton::toggled, this, &CashierDialog::onPaymentMethodChanged);

    // 控件启用状态（原逻辑保留）
    checkoutButton->setEnabled(true);
    paidAmountSpin->setEnabled(true);
    cashRadio->setEnabled(true);
    cardRadio->setEnabled(true);
    wechatRadio->setEnabled(true);
    alipayRadio->setEnabled(true);
    memberBalanceRadio->setEnabled(true);
    increaseButton->setEnabled(true);
    decreaseButton->setEnabled(true);
    deleteProductButton->setEnabled(true);
    memberCardEdit->setEnabled(true);
    clearCardButton->setEnabled(true);
}

// 析构函数
CashierDialog::~CashierDialog()
{
}

void CashierDialog::setupUI()
{
    createFirstLayer();
    createSecondLayer();
    createThirdLayer();
    createFourthLayer();
}

void CashierDialog::createFirstLayer()
{
    // 第一层：标题标签
    titleLabel = new QLabel("收银系统", this);
    titleLabel->setObjectName("titleLabel");
    titleLabel->setAlignment(Qt::AlignCenter);

    // 设置字体和样式
    QFont titleFont("Microsoft YaHei", 24, QFont::Bold);
    titleLabel->setFont(titleFont);

    // 固定高度55
    titleLabel->setFixedHeight(55);

    // 修改：确保标题标签不超出边界，设置最大宽度为窗口宽度减去边距
    titleLabel->setMaximumWidth(this->width());  // 减去左右边距

    // 添加到主布局
    mainLayout->addWidget(titleLabel);
}

void CashierDialog::createSecondLayer()
{
    // 第二层布局
    secondLayout = new QHBoxLayout();
    secondLayout->setSpacing(10);
    secondLayout->setContentsMargins(5, 5, 5, 5);  // 添加布局内边距

    // 编码标签
    codeLabel = new QLabel("编码/内码+回车：", this);
    codeLabel->setFixedWidth(120);

    // 编码输入框
    codeEdit = new QLineEdit(this);
    codeEdit->setFixedWidth(300);
    codeEdit->setPlaceholderText("请输入商品编码并按回车");

    // 清空编码按钮
    clearCodeButton = new QPushButton("删除", this);
    clearCodeButton->setFixedWidth(60);

    // 商品按钮
    productButton = new QPushButton("商品 (F1)", this);
    productButton->setFixedWidth(80);
    productButton->setShortcut(QKeySequence(Qt::Key_F1));
    productButton->setEnabled(false);  // 禁用未实现功能

    // 修改：使用弹性空间代替固定距离，避免超出屏幕
    QSpacerItem *spacer = new QSpacerItem(10, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);

    // 交易信息布局
    QHBoxLayout *transactionInfoLayout = new QHBoxLayout();
    transactionInfoLayout->setSpacing(10);  // 减小间距避免拥挤

    // 销售单号标签
    orderLabel = new QLabel("销售单号：", this);
    orderLabel->setFixedWidth(80);

    // 销售单号值标签
    orderValueLabel = new QLabel("", this);
    orderValueLabel->setFixedWidth(145);
    orderValueLabel->setStyleSheet("border: 2px solid #81c784; padding: 4px; background-color: #f1f8e9; border-radius: 4px;");

    // 交易时间标签
    timeLabel = new QLabel("交易时间：", this);
    timeLabel->setFixedWidth(80);

    // 交易时间值标签
    timeValueLabel = new QLabel(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"), this);
    timeValueLabel->setFixedWidth(180);
    timeValueLabel->setStyleSheet("border: 2px solid #81c784; padding: 4px; background-color: #f1f8e9; border-radius: 4px;");

    // 交易状态标签
    statusLabel = new QLabel("交易状态：", this);
    statusLabel->setFixedWidth(80);

    // 交易状态值标签
    statusValueLabel = new QLabel("正常", this);
    statusValueLabel->setFixedWidth(80);
    statusValueLabel->setStyleSheet("border: 2px solid #81c784; padding: 4px; background-color: #f1f8e9; border-radius: 4px;");

    // 收银员标签
    cashierLabel = new QLabel("收银员：", this);
    cashierLabel->setFixedWidth(60);

    // 收银员值标签
    cashierValueLabel = new QLabel("admin", this);
    cashierValueLabel->setFixedWidth(80);
    cashierValueLabel->setStyleSheet("border: 2px solid #81c784; padding: 4px; background-color: #f1f8e9; border-radius: 4px;");

    transactionInfoLayout->addWidget(orderLabel);
    transactionInfoLayout->addWidget(orderValueLabel);
    transactionInfoLayout->addWidget(timeLabel);
    transactionInfoLayout->addWidget(timeValueLabel);
    transactionInfoLayout->addWidget(statusLabel);
    transactionInfoLayout->addWidget(statusValueLabel);
    transactionInfoLayout->addWidget(cashierLabel);
    transactionInfoLayout->addWidget(cashierValueLabel);

    // 添加到第二层布局
    secondLayout->addWidget(codeLabel);
    secondLayout->addWidget(codeEdit);
    secondLayout->addWidget(clearCodeButton);
    secondLayout->addWidget(productButton);
    secondLayout->addItem(spacer);
    secondLayout->addLayout(transactionInfoLayout);

    // 固定高度60
    QWidget *secondLayerWidget = new QWidget(this);
    secondLayerWidget->setLayout(secondLayout);

    // 添加到主布局
    mainLayout->addWidget(secondLayerWidget);
}

void CashierDialog::createThirdLayer()
{
    // 第三层主布局
    thirdMainLayout = new QHBoxLayout();
    thirdMainLayout->setSpacing(15);
    thirdMainLayout->setContentsMargins(5, 5, 5, 5);  // 添加布局内边距

    // 左侧区域：商品列表和热销商品
    QVBoxLayout *leftLayout = new QVBoxLayout();
    leftLayout->setSpacing(10);

    // 商品表格区域
    QGroupBox *productGroup = new QGroupBox("购物车商品", this);
    QVBoxLayout *productGroupLayout = new QVBoxLayout(productGroup);
    productGroupLayout->setContentsMargins(5, 15, 5, 5);  // 调整内边距

    productTable = new QTableWidget(this);
    productTable->setColumnCount(7);
    productTable->setHorizontalHeaderLabels(QStringList() << "序号" << "商品编码" << "商品名称" << "单价" << "数量" << "金额" << "操作");
    productTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    productTable->horizontalHeader()->setSectionResizeMode(6, QHeaderView::Fixed);
    productTable->setColumnWidth(6, 150);
    productTable->setEditTriggers(QAbstractItemView::NoEditTriggers);

    productGroupLayout->addWidget(productTable);
    leftLayout->addWidget(productGroup, 3);

    // 热销商品和库存提示区域
    QHBoxLayout *bottomLeftLayout = new QHBoxLayout();
    bottomLeftLayout->setSpacing(10);

    // 热销商品树
    QGroupBox *hotProductGroup = new QGroupBox("热销商品", this);
    QVBoxLayout *hotProductLayout = new QVBoxLayout(hotProductGroup);
    hotProductLayout->setContentsMargins(5, 15, 5, 5);  // 调整内边距
    hotProductGroup->setMaximumHeight(hotProductGroup->maximumHeight() - 40);

    hotProductTree = new QTreeWidget(this);
    hotProductTree->setColumnCount(1);
    hotProductTree->setHeaderHidden(true);

    hotProductLayout->addWidget(hotProductTree);

    // 库存信息区域
    QGroupBox *stockGroup = new QGroupBox("库存信息", this);
    QVBoxLayout *stockLayout = new QVBoxLayout(stockGroup);
    stockLayout->setContentsMargins(5, 15, 5, 5);  // 调整内边距
    stockGroup->setMaximumHeight(stockGroup->maximumHeight() - 40);

    stockInfoLabel = new QLabel("请选择商品查看库存", this);
    stockInfoLabel->setWordWrap(true);
    stockLayout->addWidget(stockInfoLabel);

    bottomLeftLayout->addWidget(hotProductGroup, 3);
    bottomLeftLayout->addWidget(stockGroup, 1);

    leftLayout->addLayout(bottomLeftLayout, 1);

    // 右侧区域：支付信息和操作
    QVBoxLayout *rightLayout = new QVBoxLayout();
    rightLayout->setSpacing(10);

    // 金额汇总区域
    QGroupBox *amountGroup = new QGroupBox("金额汇总", this);
    QGridLayout *amountLayout = new QGridLayout(amountGroup);
    amountLayout->setSpacing(10);
    amountLayout->setContentsMargins(15, 15, 15, 15);

    // 金额标签
    QLabel *totalLabel = new QLabel("商品总金额：", this);
    QLabel *discountLabel = new QLabel("折扣金额：", this);
    QLabel *receivableLabel = new QLabel("应收金额：", this);
    QLabel *paidLabel = new QLabel("已付金额：", this);
    QLabel *changeLabel = new QLabel("找零金额：", this);

    // 金额值
    totalAmountLabel = new QLabel("¥ 0.00", this);
    discountAmountLabel = new QLabel("¥ 0.00", this);
    receivableAmountLabel = new QLabel("¥ 0.00", this);
    receivableAmountLabel->setObjectName("totalAmountLabel");

    // 已付金额输入
    paidAmountSpin = new QDoubleSpinBox(this);
    paidAmountSpin->setMinimum(0);
    paidAmountSpin->setDecimals(2);
    paidAmountSpin->setMaximum(99999.99);
    paidAmountSpin->setValue(0);
    paidAmountSpin->setPrefix("¥ ");
    paidAmountSpin->setEnabled(false);  // 禁用未实现功能

    changeAmountLabel = new QLabel("¥ 0.00", this);
    changeAmountLabel->setObjectName("totalAmountLabel");

    // 设置金额标签对齐方式
    totalLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    discountLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    receivableLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    paidLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    changeLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    totalAmountLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    discountAmountLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    receivableAmountLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    changeAmountLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);

    // 添加到金额布局
    amountLayout->addWidget(totalLabel, 0, 0);
    amountLayout->addWidget(totalAmountLabel, 0, 1);
    amountLayout->addWidget(discountLabel, 1, 0);
    amountLayout->addWidget(discountAmountLabel, 1, 1);
    amountLayout->addWidget(receivableLabel, 2, 0);
    amountLayout->addWidget(receivableAmountLabel, 2, 1);
    amountLayout->addWidget(paidLabel, 3, 0);
    amountLayout->addWidget(paidAmountSpin, 3, 1);
    amountLayout->addWidget(changeLabel, 4, 0);
    amountLayout->addWidget(changeAmountLabel, 4, 1);

    amountGroup->setMaximumWidth(350);
    rightLayout->addWidget(amountGroup);

    // 支付方式区域
    QGroupBox *paymentGroup = new QGroupBox("支付方式", this);
    QVBoxLayout *paymentLayout = new QVBoxLayout(paymentGroup);
    paymentLayout->setContentsMargins(10, 15, 10, 10);  // 调整内边距
    paymentGroup->setMaximumWidth(400);

    cashRadio = new QRadioButton("现金支付", this);
    cardRadio = new QRadioButton("银行卡支付", this);
    wechatRadio = new QRadioButton("微信支付", this);
    alipayRadio = new QRadioButton("支付宝支付", this);
    memberBalanceRadio = new QRadioButton("会员余额支付", this);

    cashRadio->setChecked(true);
    cashRadio->setEnabled(false);  // 禁用未实现功能
    cardRadio->setEnabled(false);
    wechatRadio->setEnabled(false);
    alipayRadio->setEnabled(false);
    memberBalanceRadio->setEnabled(false);

    paymentLayout->addWidget(cashRadio);
    paymentLayout->addWidget(cardRadio);
    paymentLayout->addWidget(wechatRadio);
    paymentLayout->addWidget(alipayRadio);
    paymentLayout->addWidget(memberBalanceRadio);

    rightLayout->addWidget(paymentGroup);

    // 交易操作区域
    QGroupBox *transactionGroup = new QGroupBox("交易操作", this);
    QVBoxLayout *transactionLayout = new QVBoxLayout(transactionGroup);
    transactionLayout->setContentsMargins(10, 15, 10, 10);  // 调整内边距
    transactionGroup->setMaximumWidth(400);

    // 小票预览按钮
    receiptPreviewButton = new QPushButton("小票预览 (F3)", this);
    receiptPreviewButton->setShortcut(QKeySequence(Qt::Key_F3));
    receiptPreviewButton->setEnabled(false);  // 禁用未实现功能

    // 打印按钮
    printButton = new QPushButton("打印小票 (F4)", this);
    printButton->setShortcut(QKeySequence(Qt::Key_F4));
    printButton->setEnabled(false);  // 禁用未实现功能

    // 挂单列表按钮
    suspendedOrderButton = new QPushButton("挂单列表 (F5)", this);
    suspendedOrderButton->setShortcut(QKeySequence(Qt::Key_F5));
    suspendedOrderButton->setEnabled(false);  // 禁用未实现功能

    transactionLayout->addWidget(receiptPreviewButton);
    transactionLayout->addWidget(printButton);
    transactionLayout->addWidget(suspendedOrderButton);

    rightLayout->addWidget(transactionGroup);

    // 结账按钮区域
    checkoutButton = new QPushButton("结账", this);
    checkoutButton->setFixedHeight(60);
    checkoutButton->setMaximumWidth(400);
    checkoutButton->setStyleSheet(
        "QPushButton {"
        "   font-size: 18px;"
        "   font-weight: bold;"
        "   background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "       stop:0 #4caf50, stop:1 #388e3c);"
        "   color: white;"
        "   border: 3px solid #2e7d32;"
        "   border-radius: 10px;"
        "   padding: 8px 12px;"
        "}"
        "QPushButton:hover {"
        "   background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "       stop:0 #66bb6a, stop:1 #4caf50);"
        "   border: 3px solid #43a047;"
        "}"
        "QPushButton:pressed {"
        "   background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "       stop:0 #2e7d32, stop:1 #1b5e20);"
        "   border: 3px solid #1b5e20;"
        "}"
    );

    rightLayout->addWidget(checkoutButton);

    // 添加左右布局到第三层主布局
    thirdMainLayout->addLayout(leftLayout, 3);
    thirdMainLayout->addLayout(rightLayout, 1);

    // 添加到主布局
    QWidget *thirdLayerWidget = new QWidget(this);
    thirdLayerWidget->setLayout(thirdMainLayout);
    mainLayout->addWidget(thirdLayerWidget, 1);
}

void CashierDialog::createFourthLayer()
{
    // 第四层主布局
    fourthMainLayout = new QHBoxLayout();
    fourthMainLayout->setSpacing(15);
    fourthMainLayout->setContentsMargins(5, 5, 5, 5);  // 添加布局内边距

    // 左侧：商品操作按钮
    QGroupBox *productOperationGroup = new QGroupBox("商品操作", this);
    QHBoxLayout *productOperationLayout = new QHBoxLayout(productOperationGroup);
    productOperationLayout->setSpacing(10);
    productOperationLayout->setContentsMargins(10, 10, 10, 10);  // 调整内边距

    // 创建商品操作按钮
    increaseButton = new QPushButton("添加 (+)", this);
    increaseButton->setObjectName("operationButton");
    increaseButton->setEnabled(false);

    decreaseButton = new QPushButton("减少 (-)", this);
    decreaseButton->setObjectName("operationButton");
    decreaseButton->setEnabled(false);

    deleteProductButton = new QPushButton("删除 (F9)", this);
    deleteProductButton->setObjectName("operationButton");
    deleteProductButton->setShortcut(QKeySequence(Qt::Key_F9));
    deleteProductButton->setEnabled(false);

    modifyPriceButton = new QPushButton("清空", this);
    modifyPriceButton->setObjectName("operationButton");
    modifyPriceButton->setEnabled(false);

    productOperationLayout->addWidget(increaseButton);
    productOperationLayout->addWidget(decreaseButton);
    productOperationLayout->addWidget(deleteProductButton);
    productOperationLayout->addWidget(modifyPriceButton);

    // 中间：会员信息区域
    QGroupBox *memberGroup = new QGroupBox("会员信息", this);
    QHBoxLayout *memberLayout = new QHBoxLayout(memberGroup);
    memberLayout->setSpacing(15);
    memberLayout->setContentsMargins(10, 10, 10, 10);  // 调整内边距

    // 创建左侧垂直布局存放会员卡号相关控件
    QVBoxLayout *memberLeftLayout = new QVBoxLayout();
    memberLeftLayout->setSpacing(8);  // 设置垂直间距

    // 会员卡号标签
    memberCardLabel = new QLabel("会员卡号：", this);
    memberCardLabel->setFixedWidth(80);

    // 会员卡号输入框和删除按钮的水平布局
    QHBoxLayout *cardInputLayout = new QHBoxLayout();
    cardInputLayout->setSpacing(5);

    // 会员卡号输入框
    memberCardEdit = new QLineEdit(this);
    memberCardEdit->setFixedWidth(150);
    memberCardEdit->setEnabled(false);  // 禁用未实现功能

    // 清空会员卡按钮
    clearCardButton = new QPushButton("删除", this);
    clearCardButton->setFixedWidth(60);
    clearCardButton->setEnabled(false);  // 禁用未实现功能

    cardInputLayout->addWidget(memberCardEdit);
    cardInputLayout->addWidget(clearCardButton);

    // 会员按钮（F11）- 移到会员卡号下方
    memberButton = new QPushButton("会员 (F11)", this);
    memberButton->setFixedWidth(215);  // 与输入框+删除按钮总宽度一致
    memberButton->setShortcut(QKeySequence(Qt::Key_F11));
    memberButton->setEnabled(false);  // 禁用未实现功能

    // 将控件添加到左侧垂直布局
    memberLeftLayout->addWidget(memberCardLabel);
    memberLeftLayout->addLayout(cardInputLayout);
    memberLeftLayout->addWidget(memberButton);

    // 会员详细信息布局
    QVBoxLayout *memberDetailLayout = new QVBoxLayout();
    QHBoxLayout *row1 = new QHBoxLayout();
    QHBoxLayout *row2 = new QHBoxLayout();
    QHBoxLayout *row3 = new QHBoxLayout();

    // 姓名
    nameLabel = new QLabel("姓名：", this);
    nameLabel->setFixedWidth(50);
    nameValueLabel = new QLabel("", this);
    nameValueLabel->setMinimumWidth(100);
    nameValueLabel->setStyleSheet("border: 2px solid #81c784; padding: 4px; background-color: #f1f8e9; border-radius: 4px;");

    // 会员等级
    levelLabel = new QLabel("等级：", this);
    levelLabel->setFixedWidth(50);
    levelValueLabel = new QLabel("", this);
    levelValueLabel->setMinimumWidth(100);
    levelValueLabel->setStyleSheet("border: 2px solid #81c784; padding: 4px; background-color: #f1f8e9; border-radius: 4px;");

    // 会员积分
    pointsLabel = new QLabel("积分：", this);
    pointsLabel->setFixedWidth(50);
    pointsValueLabel = new QLabel("", this);
    pointsValueLabel->setMinimumWidth(100);
    pointsValueLabel->setStyleSheet("border: 2px solid #81c784; padding: 4px; background-color: #f1f8e9; border-radius: 4px;");

    // 可用余额
    balanceLabel = new QLabel("余额：", this);
    balanceLabel->setFixedWidth(50);
    balanceValueLabel = new QLabel("", this);
    balanceValueLabel->setMinimumWidth(100);
    balanceValueLabel->setStyleSheet("border: 2px solid #81c784; padding: 4px; background-color: #f1f8e9; border-radius: 4px;");

    // 累计充值
    totalSpentLabel = new QLabel("累计充值：", this);
    totalSpentLabel->setFixedWidth(70);
    totalSpentValueLabel = new QLabel("", this);
    totalSpentValueLabel->setMinimumWidth(100);
    totalSpentValueLabel->setStyleSheet("border: 2px solid #81c784; padding: 4px; background-color: #f1f8e9; border-radius: 4px;");

    // 折扣率
    discountRateLabel = new QLabel("折扣率：", this);
    discountRateLabel->setFixedWidth(70);
    discountRateValueLabel = new QLabel("", this);
    discountRateValueLabel->setMinimumWidth(100);
    discountRateValueLabel->setStyleSheet("border: 2px solid #81c784; padding: 4px; background-color: #f1f8e9; border-radius: 4px;");

    row1->addWidget(nameLabel);
    row1->addWidget(nameValueLabel);
    row1->addWidget(levelLabel);
    row1->addWidget(levelValueLabel);

    row2->addWidget(pointsLabel);
    row2->addWidget(pointsValueLabel);
    row2->addWidget(balanceLabel);
    row2->addWidget(balanceValueLabel);

    row3->addWidget(totalSpentLabel);
    row3->addWidget(totalSpentValueLabel);
    row3->addWidget(discountRateLabel);
    row3->addWidget(discountRateValueLabel);

    memberDetailLayout->addLayout(row1);
    memberDetailLayout->addLayout(row2);
    memberDetailLayout->addLayout(row3);

    // 添加到会员布局
    memberLayout->addLayout(memberLeftLayout);  // 添加左侧垂直布局
    memberLayout->addLayout(memberDetailLayout);
    memberLayout->addStretch();

    // 右侧：系统功能按钮
    QGroupBox *systemFunctionGroup = new QGroupBox("系统功能", this);
    QHBoxLayout *systemFunctionLayout = new QHBoxLayout(systemFunctionGroup);
    systemFunctionLayout->setSpacing(10);
    systemFunctionLayout->setContentsMargins(10, 10, 10, 10);  // 调整内边距

    // 创建功能按钮
    lockButton = new QPushButton("锁屏 (F2)", this);
    lockButton->setShortcut(QKeySequence(Qt::Key_F2));
    lockButton->setEnabled(false);  // 禁用未实现功能

    holdButton = new QPushButton("挂单 (F6)", this);
    holdButton->setShortcut(QKeySequence(Qt::Key_F6));
    holdButton->setEnabled(false);  // 禁用未实现功能

    resumeButton = new QPushButton("取单 (F7)", this);
    resumeButton->setShortcut(QKeySequence(Qt::Key_F7));
    resumeButton->setEnabled(false);  // 禁用未实现功能

    exchangeButton = new QPushButton("退换货 (F10)", this);
    exchangeButton->setShortcut(QKeySequence(Qt::Key_F10));
    exchangeButton->setEnabled(false);  // 禁用未实现功能

    exitButton = new QPushButton("退出 (Esc)", this);
    exitButton->setShortcut(QKeySequence(Qt::Key_Escape));
    exitButton->setStyleSheet(
        "QPushButton {"
        "   background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "       stop:0 #e57373, stop:1 #d32f2f);"
        "   color: white;"
        "   border: 2px solid #c62828;"
        "   border-radius: 8px;"
        "   font: bold 10pt 'Microsoft YaHei';"
        "   padding: 8px 12px;"
        "}"
        "QPushButton:hover {"
        "   background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "       stop:0 #ef5350, stop:1 #e57373);"
        "   border: 2px solid #d32f2f;"
        "}"
        "QPushButton:pressed {"
        "   background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "       stop:0 #c62828, stop:1 #b71c1c);"
        "   border: 2px solid #b71c1c;"
        "}"
    );
    connect(exitButton, &QPushButton::clicked, this, &CashierDialog::onExitClicked);

    // 添加到系统功能布局
    systemFunctionLayout->addWidget(lockButton);
    systemFunctionLayout->addWidget(holdButton);
    systemFunctionLayout->addWidget(resumeButton);
    systemFunctionLayout->addWidget(exchangeButton);
    systemFunctionLayout->addWidget(exitButton);

    // 添加到第四层主布局
    fourthMainLayout->addWidget(productOperationGroup, 3);
    fourthMainLayout->addWidget(memberGroup, 3);
    fourthMainLayout->addWidget(systemFunctionGroup, 3);

    // 添加到主布局
    QWidget *fourthLayerWidget = new QWidget(this);
    fourthLayerWidget->setLayout(fourthMainLayout);
    mainLayout->addWidget(fourthLayerWidget);
}

// 退出按钮的槽函数实现
void CashierDialog::onExitClicked()
{
    // 关闭对话框
    this->close();
}

// 实现槽函数
void CashierDialog::onCodeEditReturnPressed()
{
    QString code = codeEdit->text().trimmed();
    if (code.isEmpty()) {
        return;
    }

    // 执行模糊搜索
    QVector<QMap<QString, QVariant>> products = m_productDAO->searchProductsByCode(code);

    if (products.size() == 1) {
        // 只有一个匹配结果，直接添加到购物车
        auto product = products.first();
        int productId = product["product_id"].toInt();
        QString productCode = product["product_code"].toString();
        QString productName = product["product_name"].toString();
        QString specification = product["specification"].toString();
        double price = product["selling_price"].toDouble();
        bool allowDiscount = product["allow_member_discount"].toBool();

        m_shoppingCart->addProduct(productId, productCode, productName, specification, price, 1, allowDiscount);
        codeEdit->clear();
    } else if (products.size() > 1) {
        // 多个匹配结果，显示选择对话框
        showProductSelectionDialog(products);
    } else {
        // 没有找到商品
        QMessageBox::warning(this, "提示", "未找到匹配的商品");
    }
}

void CashierDialog::onCartUpdated()
{
    // 更新界面显示
    updateProductTable();
    updateAmountDisplay();
}

void CashierDialog::updateProductTable()
{
    productTable->clearContents();
    productTable->setRowCount(0);

    auto items = m_shoppingCart->getItems();
    for (int i = 0; i < items.size(); ++i) {
        const auto& item = items[i];

        productTable->insertRow(i);
        productTable->setItem(i, 0, new QTableWidgetItem(QString::number(i + 1)));
        productTable->setItem(i, 1, new QTableWidgetItem(item.productCode));
        productTable->setItem(i, 2, new QTableWidgetItem(item.productName));
        productTable->setItem(i, 3, new QTableWidgetItem(QString::number(item.price, 'f', 2)));
        productTable->setItem(i, 4, new QTableWidgetItem(QString::number(item.quantity)));
        productTable->setItem(i, 5, new QTableWidgetItem(QString::number(item.subtotal, 'f', 2)));

        // 添加操作按钮
        QWidget *widget = new QWidget();
        QHBoxLayout *layout = new QHBoxLayout(widget);
        layout->setContentsMargins(2, 2, 2, 2);
        layout->setSpacing(2);

        QPushButton *increaseBtn = new QPushButton("+");
        QPushButton *decreaseBtn = new QPushButton("-");
        QPushButton *deleteBtn = new QPushButton("删");

        increaseBtn->setFixedSize(25, 25);
        decreaseBtn->setFixedSize(25, 25);
        deleteBtn->setFixedSize(40, 25);

        connect(increaseBtn, &QPushButton::clicked, this, [this, item]() {
            m_shoppingCart->updateQuantity(item.productId, item.quantity + 1);
        });

        connect(decreaseBtn, &QPushButton::clicked, this,  [this, item]() {
            m_shoppingCart->updateQuantity(item.productId, item.quantity - 1);
        });

        connect(deleteBtn, &QPushButton::clicked, this,  [this, item]() {
            m_shoppingCart->removeProduct(item.productId);
        });

        layout->addWidget(increaseBtn);
        layout->addWidget(decreaseBtn);
        layout->addWidget(deleteBtn);
        widget->setLayout(layout);

        productTable->setCellWidget(i, 6, widget);
    }
}

// 显示商品选择对话框
void CashierDialog::showProductSelectionDialog(const QVector<QMap<QString, QVariant>>& products)
{
    QDialog dialog(this);
    dialog.setWindowTitle("选择商品");
    dialog.setModal(true);
    dialog.resize(600, 400);

    QVBoxLayout *layout = new QVBoxLayout(&dialog);

    QTableWidget *table = new QTableWidget(&dialog);
    table->setColumnCount(5);
    table->setHorizontalHeaderLabels(QStringList() << "编码" << "名称" << "规格" << "价格" << "库存");
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);

    table->setRowCount(products.size());
    for (int i = 0; i < products.size(); ++i) {
        const auto& product = products[i];

        table->setItem(i, 0, new QTableWidgetItem(product["product_code"].toString()));
        table->setItem(i, 1, new QTableWidgetItem(product["product_name"].toString()));
        table->setItem(i, 2, new QTableWidgetItem(product["specification"].toString()));
        table->setItem(i, 3, new QTableWidgetItem(QString::number(product["selling_price"].toDouble(), 'f', 2)));
        // 这里需要查询库存信息
        table->setItem(i, 4, new QTableWidgetItem("有货")); // 简化显示
    }

    table->resizeColumnsToContents();

    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);

    layout->addWidget(table);
    layout->addWidget(buttonBox);

    connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    if (dialog.exec() == QDialog::Accepted) {
        int row = table->currentRow();
        if (row >= 0) {
            auto product = products[row];
            int productId = product["product_id"].toInt();
            QString productCode = product["product_code"].toString();
            QString productName = product["product_name"].toString();
            QString specification = product["specification"].toString();
            double price = product["selling_price"].toDouble();
            bool allowDiscount = product["allow_member_discount"].toBool();

            m_shoppingCart->addProduct(productId, productCode, productName, specification, price, 1, allowDiscount);
            codeEdit->clear();
        }
    }
}

// 实现结账按钮槽函数
void CashierDialog::onCheckoutButtonClicked()
{
    if (m_shoppingCart->isEmpty()) {  // 智能指针用->访问成员（与原始指针一致，无语法变化）
        QMessageBox::warning(this, "提示", "购物车为空，无法结账");
        return;
    }

    // 获取支付方式（原逻辑保留）
    PaymentMethod paymentMethod = PAYMENT_CASH;
    if (cashRadio->isChecked()) paymentMethod = PAYMENT_CASH;
    else if (cardRadio->isChecked()) paymentMethod = PAYMENT_CARD;
    else if (wechatRadio->isChecked()) paymentMethod = PAYMENT_WECHAT;
    else if (alipayRadio->isChecked()) paymentMethod = PAYMENT_ALIPAY;
    else if (memberBalanceRadio->isChecked()) paymentMethod = PAYMENT_MEMBER_BALANCE;

    // -------------------------- 智能指针修改开始 --------------------------
    // 智能指针用->访问成员（与原始指针一致，仅标注确认无修改）
    if (!m_paymentProcessor->isPaymentMethodAvailable(paymentMethod, m_currentCustomerId)) {
        QString methodName = PaymentProcessor::getPaymentMethodName(paymentMethod);
        QMessageBox::warning(this, "警告", QString("%1不可用").arg(methodName));
        return;
    }
    // -------------------------- 智能指针修改结束 --------------------------

    // 获取当前用户ID（原逻辑保留）
    int userId = 1; // 假设当前用户ID为1

    // -------------------------- 智能指针修改开始 --------------------------
    // 1. 智能指针用->访问成员（createOrderFromCart）
    int orderId = m_orderService->createOrderFromCart(*m_shoppingCart, userId, m_currentCustomerId, paymentMethod);
    // -------------------------- 智能指针修改结束 --------------------------

    if (orderId > 0) {
        m_currentOrderId = orderId;

        // -------------------------- 智能指针修改开始 --------------------------
        // 1. 智能指针用->访问成员（getTotal、processPayment）
        double totalAmount = m_shoppingCart->getTotal();
        bool paymentSuccess = m_paymentProcessor->processPayment(orderId, paymentMethod, totalAmount, "", m_currentCustomerId);
        // 2. 智能指针用->访问成员（payOrder、getPaymentResult）
        if (paymentSuccess) {
            m_orderService->payOrder(orderId, paymentMethod,
                                   m_paymentProcessor->getPaymentResult()["transactionNo"].toString());
        }
        // -------------------------- 智能指针修改结束 --------------------------
        else {
            QMessageBox::warning(this, "支付失败", "支付处理失败，请重试或选择其他支付方式");
        }
    }
}

// 清空购物车
void CashierDialog::onClearCartButtonClicked()
{
    if (QMessageBox::question(this, "确认", "确定要清空购物车吗？") == QMessageBox::Yes) {
        // -------------------------- 智能指针修改开始 --------------------------
        // 智能指针用->访问成员（clear），与原始指针一致
        m_shoppingCart->clear();
        // -------------------------- 智能指针修改结束 --------------------------

        // 原逻辑保留（非智能指针相关）
        m_currentOrderId = 0;
        m_currentCustomerId = 0;
        m_customerDiscountRate = 1.0;
        nameValueLabel->setText("");
        levelValueLabel->setText("");
        pointsValueLabel->setText("");
        balanceValueLabel->setText("");
        totalSpentValueLabel->setText("");
        discountRateValueLabel->setText("");
        paidAmountSpin->setValue(0);
        cashRadio->setChecked(true);
        resetOrderDisplay();
    }
}

// 会员卡号输入处理
void CashierDialog::onMemberCardEditReturnPressed()
{
    QString cardNumber = memberCardEdit->text().trimmed();
    if (cardNumber.isEmpty()) {
        return;
    }

    // -------------------------- 智能指针修改开始 --------------------------
    // 智能指针用->访问成员（getMemberByCard、applyDiscount）
    QMap<QString, QVariant> memberInfo = m_memberDAO->getMemberByCard(cardNumber);
    // ... 中间逻辑保留 ...
    m_shoppingCart->applyDiscount(m_customerDiscountRate);
    // -------------------------- 智能指针修改结束 --------------------------

    // 原逻辑保留（非智能指针相关）
    if (memberInfo.isEmpty()) {
        QMessageBox::warning(this, "提示", "未找到该会员卡号");
        return;
    }
    m_currentCustomerId = memberInfo["customer_id"].toInt();
    nameValueLabel->setText(memberInfo["name"].toString());
    levelValueLabel->setText(memberInfo["level_name"].toString());
    pointsValueLabel->setText(QString::number(memberInfo["points"].toInt()));
    balanceValueLabel->setText(QString::number(memberInfo["balance"].toDouble(), 'f', 2));
    totalSpentValueLabel->setText(QString::number(memberInfo["total_spent"].toDouble(), 'f', 2));
    m_customerDiscountRate = memberInfo["discount_rate"].toDouble();
    discountRateValueLabel->setText(QString::number(m_customerDiscountRate * 10, 'f', 1) + "折");
    updateAmountDisplay();
}

// 清空会员卡号
void CashierDialog::onClearCardButtonClicked()
{
    // 原逻辑保留（非智能指针相关）
    memberCardEdit->clear();
    m_currentCustomerId = 0;
    m_customerDiscountRate = 1.0;
    nameValueLabel->setText("");
    levelValueLabel->setText("");
    pointsValueLabel->setText("");
    balanceValueLabel->setText("");
    totalSpentValueLabel->setText("");
    discountRateValueLabel->setText("");

    // -------------------------- 智能指针修改开始 --------------------------
    // 智能指针用->访问成员（applyDiscount）
    m_shoppingCart->applyDiscount(1.0);
    // -------------------------- 智能指针修改结束 --------------------------

    updateAmountDisplay(); // 原逻辑保留
}

// 已付金额变化处理
void CashierDialog::onPaidAmountChanged(double amount)
{
    double total = m_shoppingCart->getTotal();
    double change = amount - total;

    if (change >= 0) {
        changeAmountLabel->setText(QString("¥ %1").arg(change, 0, 'f', 2));
        changeAmountLabel->setStyleSheet("color: green;");
    } else {
        changeAmountLabel->setText(QString("¥ %1").arg(change, 0, 'f', 2));
        changeAmountLabel->setStyleSheet("color: red;");
    }
}

// 支付方式变化处理
void CashierDialog::onPaymentMethodChanged()
{
    // 获取当前选择的支付方式
    PaymentMethod selectedMethod = PAYMENT_CASH;
    if (cashRadio->isChecked()) selectedMethod = PAYMENT_CASH;
    else if (cardRadio->isChecked()) selectedMethod = PAYMENT_CARD;
    else if (wechatRadio->isChecked()) selectedMethod = PAYMENT_WECHAT;
    else if (alipayRadio->isChecked()) selectedMethod = PAYMENT_ALIPAY;
    else if (memberBalanceRadio->isChecked()) selectedMethod = PAYMENT_MEMBER_BALANCE;

    // 检查支付方式是否可用
    bool isAvailable = m_paymentProcessor->isPaymentMethodAvailable(selectedMethod, m_currentCustomerId);

    if (!isAvailable && selectedMethod == PAYMENT_MEMBER_BALANCE) {
        QMessageBox::information(this, "提示", "请先输入会员卡号才能使用会员余额支付");
        cashRadio->setChecked(true);
    }
}

// 订单创建成功
void CashierDialog::onOrderCreated(int orderId)
{
    // 更新订单号显示
    orderValueLabel->setText(QString::number(orderId));

    // 使用动画效果更新订单状态
    animateStatusChange("待支付", "color: orange; border: 1px solid #ccc; padding: 2px;");

    // 记录当前订单ID
    m_currentOrderId = orderId;

    qDebug() << "订单创建成功:" << orderId;
}

// 订单支付成功
void CashierDialog::onOrderPaid(int orderId)
{
    // 使用动画效果更新订单状态
    animateStatusChange("已支付", "color: green; border: 1px solid #ccc; padding: 2px;");

    // 更新支付时间
    timeValueLabel->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));

    // 显示成功消息
    QMessageBox::information(this, "成功", QString("订单支付成功！订单号: %1").arg(orderId));

    // 清空购物车
    m_shoppingCart->clear();
    updateProductTable();
    updateAmountDisplay();

    // 延迟2秒后重置订单显示
    QTimer::singleShot(2000, this, &CashierDialog::resetOrderDisplay);

    qDebug() << "订单支付成功:" << orderId;
}

// 订单错误处理
void CashierDialog::onOrderError(const QString &errorMessage)
{
    QMessageBox::critical(this, "错误", errorMessage);
}

// 更新金额显示（修改原有函数）
void CashierDialog::updateAmountDisplay()
{
    // -------------------------- 智能指针修改开始 --------------------------
    // 智能指针用->访问成员（calculateSubtotal、getDiscountAmount、getTotal）
    double subtotal = m_shoppingCart->calculateSubtotal();
    double discount = m_shoppingCart->getDiscountAmount();
    double total = m_shoppingCart->getTotal();
    // -------------------------- 智能指针修改结束 --------------------------

    // 原逻辑保留（非智能指针相关）
    totalAmountLabel->setText(QString("¥ %1").arg(subtotal, 0, 'f', 2));
    discountAmountLabel->setText(QString("¥ %1").arg(discount, 0, 'f', 2));
    receivableAmountLabel->setText(QString("¥ %1").arg(total, 0, 'f', 2));
    double paid = paidAmountSpin->value();
    double change = paid - total;
    if (change >= 0) {
        changeAmountLabel->setText(QString("¥ %1").arg(change, 0, 'f', 2));
        changeAmountLabel->setStyleSheet("color: green;");
    } else {
        changeAmountLabel->setText(QString("¥ %1").arg(change, 0, 'f', 2));
        changeAmountLabel->setStyleSheet("color: red;");
    }
}

// 添加重置订单显示的方法
void CashierDialog::resetOrderDisplay()
{
    orderValueLabel->setText("--");
    statusValueLabel->setText("待支付");
    statusValueLabel->setStyleSheet("color: orange; border: 1px solid #ccc; padding: 2px;");
    timeValueLabel->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
}

void CashierDialog::initAnimations()
{
    // -------------------------- 智能指针修改开始 --------------------------
    // 修改：new QPropertyAnimation → std::make_unique（智能指针管理）
    m_statusAnimation = std::make_unique<QPropertyAnimation>(statusValueLabel, "styleSheet", this);
    // -------------------------- 智能指针修改结束 --------------------------
    m_statusAnimation->setDuration(500);  // 原逻辑保留（智能指针用->访问成员，与原始指针一致）
}

//动画状态变化函数
void CashierDialog::animateStatusChange(const QString& newStatus, const QString& newStyle)
{
    // 原逻辑保留（非智能指针相关）
    QString currentStyle = statusValueLabel->styleSheet();

    // -------------------------- 智能指针修改开始 --------------------------
    // 智能指针用->访问成员（setStartValue、setEndValue、start）
    m_statusAnimation->setStartValue(currentStyle);
    m_statusAnimation->setEndValue(newStyle);
    // -------------------------- 智能指针修改结束 --------------------------

    // 原逻辑保留（非智能指针相关）
    statusValueLabel->setText(newStatus);
    m_statusAnimation->start();
}

void CashierDialog::onPaymentCompleted(int orderId, bool success, const QString &message)
{
    if (success) {
        // -------------------------- 智能指针修改开始 --------------------------
        // 智能指针用->访问成员（getPaymentResult、clear）
        QMap<QString, QVariant> paymentResult = m_paymentProcessor->getPaymentResult();
        // ... 中间逻辑保留 ...
        m_shoppingCart->clear();
        // -------------------------- 智能指针修改结束 --------------------------

        // 原逻辑保留（非智能指针相关）
        QString transactionNo = paymentResult["transactionNo"].toString();
        QString methodName = paymentResult["methodName"].toString();
        animateStatusChange("已支付", "color: green; border: 1px solid #ccc; padding: 2px;");
        QMessageBox::information(this, "支付成功",
                                QString("订单支付成功！\n订单号: %1\n支付方式: %2\n交易号: %3")
                                .arg(orderId).arg(methodName).arg(transactionNo));
        updateProductTable();
        updateAmountDisplay();
        QTimer::singleShot(2000, this, &CashierDialog::resetOrderDisplay);
    } else {
        QMessageBox::warning(this, "支付失败", message);
    }
}
